<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-select
        v-model="listQuery.bundleId"
        placeholder="包名"
      >
        <el-option
          v-for="(bundle, i) in bundleIds"
          :key="i"
          :label="bundle"
          :value="bundle"
        />
      </el-select>
      <el-select
        v-model="listQuery.channelName"
        placeholder="渠道"
        filterable
      >
        <el-option
          v-for="(channel, i) in channels"
          :key="i"
          :label="channel"
          :value="channel"
        />
      </el-select>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        type="info"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetFilter"
      >重置</el-button>
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <div class="cs-filter-result">
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          label="包名"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.bundleId }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="渠道名称"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.channelName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.createAt | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.updateAt | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="配置状态"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              :type="scope.row.status === 0 ? 'primary' : 'danger'"
              size="mini"
              @click="editStatus(scope.row)"
            >{{ scope.row.status === 1 ? '审核' : '普通' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="所属端"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.type === 1 ? 'IOS' : '安卓' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="版本名称"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ handleVersion(scope.row.versionStart) }}~~~{{ handleVersion(scope.row.versionEnd) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              type="primary"
              size="mini"
              @click="handleUpdate(row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <TablePagination
        :current-page="listQuery.page"
        :limit="listQuery.limit"
        :total="total"
        :loading="listLoading"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item
          label="包名:"
          prop="bundleId"
        >
          <el-input v-model.trim="temp.bundleId" maxlength="40" />
        </el-form-item>
        <el-form-item
          label="渠道名称:"
          prop="channelName"
        >
          <el-input v-model.trim="temp.channelName" maxlength="20" />
        </el-form-item>
        <el-form-item
          label="开始版本:"
          prop="startVersion"
        >
          <el-input-number
            v-model="temp.startVersion.first"
            style="width: 50px;"
            :min="1"
            size="medium"
            :controls="false"
          />
          <span>.</span>
          <el-input-number
            v-model="temp.startVersion.second"
            style="width: 50px;"
            :min="0"
            :max="99"
            size="medium"
            :controls="false"
          />
          <span>.</span>
          <el-input-number
            v-model="temp.startVersion.last"
            style="width: 50px;"
            :min="0"
            :max="99"
            size="medium"
            :controls="false"
          />
        </el-form-item>
        <el-form-item
          label="终止版本:"
          prop="endVersion"
        >
          <el-input-number
            v-model="temp.endVersion.first"
            style="width: 50px;"
            :min="1"
            size="medium"
            :controls="false"
          />
          <span>.</span>
          <el-input-number
            v-model="temp.endVersion.second"
            style="width: 50px;"
            :min="0"
            :max="99"
            size="medium"
            :controls="false"
          />
          <span>.</span>
          <el-input-number
            v-model="temp.endVersion.last"
            style="width: 50px;"
            :min="0"
            :max="99"
            size="medium"
            :controls="false"
          />
        </el-form-item>
        <el-form-item
          label="状态:"
          prop="status"
        >
          <el-select
            v-model="temp.status"
            placeholder="请选择"
          >
            <el-option
              v-for="item in optionsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="所属端:"
          prop="type"
        >
          <el-select
            v-model="temp.type"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TablePagination from '@/components/TablePagination' // secondary package based on el-pagination
import {
  getChannelList,
  updateChannelList,
  editChannelStatus,
  deleteChannelList
} from '@/api/customSetting'
import {
  xhrChannels
} from '@api/analysis'
export default {
  name: 'ChannelsSetting',
  components: { TablePagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      channels: [],
      bundleIds: ['com.vchat.flower', 'com.vchat.flower.ios', 'com.date.flower', 'com.date.flower.ios'],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      temp: {
        id: undefined,
        bundleId: null,
        channelName: null,
        version: null,
        startVersion: {
          first: null,
          second: null,
          last: null
        },
        endVersion: {
          first: null,
          second: null,
          last: null
        },
        type: 0,
        status: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      total: 0,
      rules: {
        bundleId: [{ required: true, message: '必选项', trigger: 'blur' }],
        startVersion: [{ required: true, message: '必选项', trigger: 'blur' }],
        endVersion: [{ required: true, message: '必选项', trigger: 'blur' }],
        status: [{ required: true, message: '必选项', trigger: 'blur' }],
        type: [{ required: true, message: '必选项', trigger: 'blur' }]
      },
      options: [
        {
          value: 0,
          label: '安卓'
        },
        {
          value: 1,
          label: 'IOS'
        }
      ],
      optionsStatus: [
        {
          value: 0,
          label: '普通'
        },
        {
          value: 1,
          label: '审核'
        }
      ],
      downloadLoading: false
    }
  },
  created() {
    this.getChannels()
    this.doSearch()
  },
  methods: {
    getChannels() {
      xhrChannels().then(resp => {
        // console.log(resp)
        this.channels = resp.data
      })
    },
    doSearch() {
      this.listLoading = true
      getChannelList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        bundleId: null,
        channelName: null,
        version: null,
        startVersion: {
          first: null,
          second: null,
          last: null
        },
        endVersion: {
          first: null,
          second: null,
          last: null
        },
        type: 0,
        status: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const { startVersion, endVersion } = this.temp
          const versionStart =
            startVersion.first * 10000 +
            startVersion.second * 100 +
            startVersion.last
          const versionEnd =
            endVersion.first * 10000 + endVersion.second * 100 + endVersion.last
          const tempData = Object.assign({}, this.temp, {
            versionStart,
            versionEnd
          })
          tempData.createAt && delete tempData.createAt
          tempData.updateAt && delete tempData.updateAt
          updateChannelList(tempData).then(() => {
            this.doSearch()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleVersionToObject(version) {
      const first = parseInt(version / 10000)
      const second = parseInt((version % 10000) / 100)
      const last = parseInt((version % 10000) % 100)
      return { first, second, last }
    },
    handleUpdate(row) {
      const { versionStart, versionEnd } = row
      const startVersion = this.handleVersionToObject(versionStart)
      const endVersion = this.handleVersionToObject(versionEnd)
      this.temp = Object.assign({}, row, { startVersion, endVersion })
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    editStatus(row) {
      this.$confirm(
        `是否修改状态为${row.status === 1 ? '普通' : '审核'}?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const status = row.status === 1 ? 0 : 1
          editChannelStatus({ id: row.id, status }).then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.doSearch()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    handleVersion(version) {
      const first = parseInt(version / 10000)
      const second = parseInt((version % 10000) / 100)
      const last = parseInt((version % 10000) % 100)
      return `${first}.${second}.${last}`
    },
    handleDelete(row) {
      this.$confirm(`是否删除此内容?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteChannelList({ id: row.id }).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.doSearch()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>
